//
//  PicturePickerController.swift
//  照片选择器
//
//  Created by 002 on 15/10/27.
//  Copyright © 2015年 002. All rights reserved.
//

import UIKit

private let PicturePickerCellId = "PicturePickerCellId"

class PicturePickerController: UICollectionViewController {

    // 最大浏览数量
    let picturePickerMaxCount = 8
    // 所选中的图片索引
    private var selectedIndex = 0
    
    
    // 浏览图片的数组
    lazy var pictures = [UIImage]()
    
    // MARK: - 构造函数
    init() {
        
        super.init(collectionViewLayout: PicturePickerLayout())
        collectionView?.backgroundColor = UIColor(white: 0.9, alpha: 1.0)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes
        self.collectionView!.registerClass(PicturePickerCell.self, forCellWithReuseIdentifier: PicturePickerCellId)

        // Do any additional setup after loading the view.
    }
    
    // MARK: - 照片布局选择器
    /// 类中类，只能被PicturePickerController所调用
    private class PicturePickerLayout : UICollectionViewFlowLayout {
        
        private override func prepareLayout() {
            // 每行显示4个item
            let count = CGFloat(4)
            // item边距
            let margin = UIScreen.mainScreen().scale * 4
            // 宽度
            let width = (UIScreen.mainScreen().bounds.width - margin * (count + 1)) / count
            
            itemSize = CGSize.init(width: width, height: width)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
            sectionInset = UIEdgeInsets.init(top: margin, left: margin, bottom: 0, right: margin)
        }
    }
}

// MARK: UICollectionViewDataSource
extension PicturePickerController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        // 保证末尾有一个 ‘+’按钮 并且 不超过上限
        return pictures.count + (pictures.count == picturePickerMaxCount ? 0 : 1)
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PicturePickerCellId, forIndexPath: indexPath) as! PicturePickerCell

        // 设置代理
        cell.delegate = self
        
        // 设置图像
        cell.image = (indexPath.item < pictures.count) ? pictures[indexPath.item] : nil

        return cell
    }
}

// MARK: - UIImagePickerControllerDelegate, UINavigationControllerDelegate
extension PicturePickerController : UIImagePickerControllerDelegate,
                                    UINavigationControllerDelegate
{
    
    /// 照片选择完成
    ///
    /// :param: picker 照片选择控制器
    /// :param: info   info 字典
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        print(info)
        
        if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage {
            
            let scaleImage = image.scaleWidth(600)
            if selectedIndex >= pictures.count {
                // 把选择的照片添加到图片数组
                pictures.append(scaleImage)
            } else {
                // 替换图片
                pictures[selectedIndex] = scaleImage
            }
            
            // 刷新视图
            collectionView?.reloadData()
        }
        
        // 释放控制器 - 因为实现了代理，所以需要自己释放
        dismissViewControllerAnimated(true, completion: nil)
    }
}

// MARK: - PicturePickerCellDelegate
extension PicturePickerController : PicturePickerCellDelegate {
    
    @objc private func picturePickerCellDidAdd(cell: PicturePickerCell) {
        
        /// 判断是否允许访问相册
        ///
        /// @param UIImagePickerControllerSourceType.PhotoLibrary
        /**
        PhotoLibrary            保存的照片(可以删除) + 同步的照片(不允许删除)
        SavedPhotosAlbum        保存的照片/屏幕截图/拍照
        */
        if !UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            print("不允许访问相册")
            return
        }
        
        // 添加图片的时候记录索引（用来判断是否越界）
        selectedIndex = collectionView?.indexPathForCell(cell)?.item ?? 0
        
        let picker = UIImagePickerController()
        // 设置代理
        picker.delegate = self
        // - picker.allowsEditing = true
        picker.allowsEditing = true
        
        presentViewController(picker, animated: true, completion: nil)
    }
    
    @objc private func picturePickerCellDidRemove(cell: PicturePickerCell) {
    
        // 1. 获取所要删除图片的索引
        let indexPath = collectionView?.indexPathForCell(cell)
        
        // 2. 判断要删除的图片是否越界
        if indexPath?.item >= pictures.count {
            return
        }
        
        //  3. 从图片数组中删除
        pictures.removeAtIndex((indexPath?.item)!)

        // 4. 刷新数据
        collectionView?.reloadData()
    }
}

// MARK: - cell的协议
/// 如果协议中包含 optional 的函数，协议需要使用 @objc 修饰
@objc
private protocol PicturePickerCellDelegate : NSObjectProtocol {
    
    // 添加照片
    optional func picturePickerCellDidAdd(cell: PicturePickerCell)
    
    // 删除照片
    optional func picturePickerCellDidRemove(cell: PicturePickerCell)
}


// 照片选择器的cell
private class PicturePickerCell : UICollectionViewCell {
    
    // 照片选择代理对象
    weak var delegate : PicturePickerCellDelegate?
    
    // 照片
    var image : UIImage? {
        didSet{
            addButton.setImage(image ?? UIImage.init(named: "compose_pic_add"), forState: UIControlState.Normal)
            // image == nil说明是新增按钮
            removeButton.hidden = (image == nil)
        }
    }
    
    // MARK: - 监听方法
    @objc private func addPicture() {
        delegate?.picturePickerCellDidAdd?(self)
    }
    
    @objc private func removePicture() {
        delegate?.picturePickerCellDidRemove?(self)
    }
    
    /// 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - 布局cell里面的控件
    func setupUI() {
        
        // 1. 添加控件
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        // 2. 布局
        // 1)添加按钮
        addButton.frame = bounds
        // 2) 删除按钮
       removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        
        // 3. 添加监听方法
        addButton.addTarget(self, action: "addPicture", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "removePicture", forControlEvents: .TouchUpInside)
        
        // 4. 设置填充模式
        addButton.imageView?.contentMode = .ScaleAspectFill
    }
    
    // MARK: - 懒加载控件
    // 添加按钮
    private lazy var addButton : UIButton = UIButton.init(imageName: "compose_pic_add", backImageName: nil)
    // 删除按钮
    private lazy var removeButton : UIButton = UIButton.init(imageName: "compose_photo_close", backImageName: nil)
}